/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package su.samlib.informer.utils.updaters;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.text.Html;

import su.samlib.informer.model.Author;

/**
 *
 * @author rikland
 */
public abstract class AbstractBooksUpdater implements BooksUpdater {

    private static final String ENCODING = "windows-1251";
    private static final String USER_AGENT = "Android reader";
    
    private boolean compressionEnabled = false;
    /**
     * Формирует URL запроса страницы автора для конкретной библиотеки
     * @return URL запрос для конкретной библиотеки
     */
    protected abstract URL getRequestURL();

    @Override
    public void setEnabledCompression(boolean compressionEnabled) {
        this.compressionEnabled = compressionEnabled;
    }
    /**
     * Формирует URL страницы автора
     * @param a автор
     * @return URL страницы автора
     */
    protected String getAuthorUrl(final Author a){
        final String libraryUrl = a.getLibraryId().getLibraryUrl();
        final String libraryUri = a.getAuthorUri();
        return libraryUrl + libraryUri;
    }
    /**
     * Настройка параметрова соединения
     * @param connection HTTP соединение
     */
    protected void setConnectionPropherties(final HttpURLConnection connection) {
        connection.addRequestProperty("User-Agent", USER_AGENT);
        connection.addRequestProperty("Connection", "Keep-Alive");
        connection.addRequestProperty("Accept", "text/html");
        connection.addRequestProperty("Accept-Charset", ENCODING);
        if(!compressionEnabled) {
            connection.addRequestProperty("Accept-Encoding", "identity");
        }
    }

    private String doReadPage(BufferedReader in) throws IOException {
        StringBuilder sb = new StringBuilder();
        String inputLine = in.readLine();
        while (inputLine != null) {
            sb.append(inputLine);
            inputLine = in.readLine();
        }
        return sb.toString();
    }
    
    /**
     * Скачивает и возвращает страницу автора
     * @return страница автора
     */
    protected String getAuthorPage() {
        String result = "";
        URL requestUrl = getRequestURL();
        try {
            HttpURLConnection serviceConnection = (HttpURLConnection) requestUrl.openConnection();
            try {
                setConnectionPropherties(serviceConnection);
                InputStream is = serviceConnection.getInputStream();
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        is, ENCODING));
                result = doReadPage(in);
            } finally {
                serviceConnection.disconnect();
            }

        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }
    
    /**
     * Чистит текст от html включений
     * @param value html текст
     * @return Чистый текст
     */
    public String unescapeAndCleanHtml(final String value) {
    	return Html.fromHtml(value).toString();
    }
    
}
